﻿//using EasyHttp.Http;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;


namespace Dt261
{
   
    class Http:HttpClient
    {
        private static Http http;
        //public const string HOST = "http://www.douting.com.cn/";
        //public const string HOST = "http://work.xiaosee.top:8099/";
#if DEBUG
       // http://work.xiaosee.top:6681/tlyht/formal/tlj/uploadMemberList
        public const string HOST = "http://douting.com.cn/";
#else
        public const string HOST = "https://douting.com.cn/";
#endif

        public static string PostHost = GlobalData.Host;

        public string exception;
        public string ContentType { get; set; } = "application/x-www-form-urlencoded";
        public static Http SharedHttp() {

            if(http == null)
            {
                var handler = new HttpClientHandler() { UseCookies = true };
                var client = new Http(handler);// { BaseAddress = baseAddress };
                client.Timeout = TimeSpan.FromSeconds(5);
                client.BaseAddress = new Uri(HOST);
                client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
                client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
                client.DefaultRequestHeaders.Add("Keep-Alive", "timeout=100");
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("app-version", "pc_"+ System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
                client.DefaultRequestHeaders.Add("app-product", "www.tinglibao.com.cn");
                client.DefaultRequestHeaders.Add("app-channel", "pc_market");
                client.DefaultRequestHeaders.Add("system-version", "Windows"+ ComputerInfo.WinMajorVersion+"_"+ ComputerInfo.WinMinorVersion);
                client.DefaultRequestHeaders.Add("device-model", ""+ Dns.GetHostName());
                client.DefaultRequestHeaders.Add("system-product", ComputerInfo.WinProductName+"_tinglibao_pc");
                client.DefaultRequestHeaders.Add("location-latitude", "0.0");
                client.DefaultRequestHeaders.Add("location-longitude", "0.0");
                client.DefaultRequestHeaders.Add("location-latitude", "0.0");
                client.DefaultRequestHeaders.Add("X-Access-Token", "");
                //client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");
                http = client;
            }
  
            return http; 
        }
        private Http(HttpClientHandler handler)
        {
            //this.Request.Accept = HttpContentTypes.ApplicationJson;
            //this.Request.ContentType = HttpContentTypes.ApplicationJson;

            //this.Request.AddExtraHeader("app-version", "pc_1.0");
            //this.Request.AddExtraHeader("app-product", "www.tinglibao.com.cn");
            //this.Request.AddExtraHeader("app-channel", "pc_market");
            //this.Request.AddExtraHeader("system-version", "win10");
            //this.Request.AddExtraHeader("device-model", "win10-pc");
            //this.Request.AddExtraHeader("system-product", "tinglibao_pc");
            //this.Request.AddExtraHeader("location-latitude", "0");
            //this.Request.AddExtraHeader("location-longitude", "0");


            //this.Request.AddExtraHeader("X-Access-Token", "0");
           // this.Request.AddExtraHeader("Cookie", "0");
        

        }

        public string GetMultipartResponse(MultipartFormDataContent content, string url = "", string method = "post", string referer = "", string EnCode = "")
        {
            if (!string.IsNullOrEmpty(referer)) http.DefaultRequestHeaders.Referrer = new Uri(referer);

            //content.Add(new ByteArrayContent(data), key, "gz-3.png");
            //MultipartFormDataContent content =  new MultipartFormDataContent();
            //HttpContent content = //new StringContent(json);
            //    new StringContent(json, Encoding.UTF8, "application/json");
//#if DEBUG
//            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
//#else
            content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data"); 
//#endif

            Uri uri = new Uri(url);

            //_client.DefaultRequestHeaders.Remove("Accept-Charset");
            //_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", EnCode);
            HttpResponseMessage res = null;
            try
            {
                if (method.ToLower().Equals("get"))
                {
                    res = http.GetAsync(uri).Result;
                }
                else res = http.PostAsync(uri, content).Result;

                if (res != null && res.IsSuccessStatusCode)
                {

                    return res.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    exception = res == null ? "服务器不响应" : Enum.GetName(typeof(HttpStatusCode), res.StatusCode);
                    return null;
                }
            }
            catch (Exception ex)
            {
                exception = ex.Message;
                return null;
            }
        }
        public string GetJSonResponse(string json, string url = "", string method = "post", string referer = "", string EnCode = "")
        {
            if (!string.IsNullOrEmpty(referer)) http.DefaultRequestHeaders.Referrer = new Uri(referer);

            HttpContent content = //new StringContent(json);
                new StringContent(json, Encoding.UTF8, "application/json");

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); ;

            Uri uri = new Uri(url);

            //_client.DefaultRequestHeaders.Remove("Accept-Charset");
            //_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", EnCode);
            HttpResponseMessage res = null;
            try
            {
                if (method.ToLower().Equals("get"))
                {
                    res = http.GetAsync(uri).Result;
                }
                else res = http.PostAsync(uri, content).Result;

                if (res != null && res.IsSuccessStatusCode)
                {

                    return res.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    exception = res == null ? "服务器不响应" : Enum.GetName(typeof(HttpStatusCode), res.StatusCode);
                    return null;
                }
            }
            catch (Exception ex)
            {
                exception = ex.Message;
                return null;
            }
        }

        public string GetResponse(HttpContent content, string url = "", string method = "get", string referer = "", string EnCode = "")
        {
            if (!string.IsNullOrEmpty(referer)) http.DefaultRequestHeaders.Referrer = new Uri(referer);

            //HttpContent content = new StringContent(data);
            if(content != null)
                content.Headers.ContentType = new MediaTypeHeaderValue(ContentType);

            Uri uri = new Uri(url);

            //_client.DefaultRequestHeaders.Remove("Accept-Charset");
            //_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", EnCode);
            HttpResponseMessage res = null;
            try
            {
                if (method.ToLower().Equals("get"))
                {
                    res =  http.GetAsync(uri).Result;
                }
                else res =  http.PostAsync(uri, content).Result;

                if (res != null && res.IsSuccessStatusCode)
                {
                    //try
                    //{
                    //    CookieCollection cookieCollection = handler.CookieContainer.GetCookies(uri);
                    //    var list = new List<string>();
                    //    if (cookieCollection.Count > 0)
                    //    {
                    //        for (int i = 0; i < cookieCollection.Count; i++)
                    //        {
                    //            list.Add(cookieCollection[i].Name + "=" + cookieCollection[i].Value + "=" + cookieCollection[i].Domain);
                    //        }
                    //        Cookie = string.Join("|", list);
                    //    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    exception = ex.Message;
                    //    return null;
                    //}

                    //referer = res.RequestMessage.RequestUri.ToString();

                    //if (referer.Contains("/(") && referer.Contains(")/"))
                    //{
                    //    useTagCode = true;
                    //    TagCode = referer.Remove(0, referer.IndexOf("(") + 1);//获取识别码
                    //    TagCode = TagCode.Remove(TagCode.IndexOf(")"), TagCode.Length - TagCode.IndexOf(")"));
                    //}

                    //res.Content.Headers.ContentType.CharSet = EnCode;
                    return  res.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    exception = res == null ? "服务器不响应" : Enum.GetName(typeof(HttpStatusCode), res.StatusCode);
                    return null;
                }
            }
            catch (Exception ex)
            {
                exception = ex.Message;
                return null;
            }
        }

        public async Task<Bitmap> GetPicture(string url, string method = "get", bool x2 = true, string data = "", string referer = "")
        {
            if (!string.IsNullOrEmpty(referer)) http.DefaultRequestHeaders.Referrer = new Uri(referer);

            HttpContent content = new StringContent(data);
           // content.Headers.ContentType = new MediaTypeHeaderValue("image/Gif");

            HttpResponseMessage res;

            if (method.ToLower().Equals("get"))
            {
                res = await http.GetAsync(new Uri(url));
            }
            else res = await http.PostAsync(new Uri(url), content);

            if (res.IsSuccessStatusCode)
            {
                var stream = await res.Content.ReadAsStreamAsync();
                Bitmap bitmap = new Bitmap(stream);
                return x2 ? ResizeImage(bitmap, bitmap.Width * 2, bitmap.Height * 2) : bitmap;
            }
            else return null;
        }

        /// <summary>
        /// 修改图片尺寸
        /// </summary>
        /// <param name="bmp"></param>
        /// <param name="newW"></param>
        /// <param name="newH"></param>
        /// <returns></returns>
        public static Bitmap ResizeImage(Bitmap bmp, int newW, int newH)
        {
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);
                // 插值算法的质量
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();
                return b;
            }
            catch
            {
                return null;
            }
         }


        public static string HttpDownloadFile(string url)
        {
            using (var client = new WebClient())
            {

                try
                {
                    var basePath = Environment.CurrentDirectory;
                    var filename = Path.GetFileNameWithoutExtension(url);
                    string tempFile = System.IO.Path.Combine(basePath, "cache", filename);

                    string dir = Path.Combine(basePath, "cache");
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    //string tempFile = Path.GetTempFileName();
                    if (!File.Exists(tempFile))
                    {
                        client.DownloadFile(url, tempFile);//下载临时文件
                        Console.WriteLine("Using 网络" + tempFile);
                    }
                    else
                    {
                        Console.WriteLine("Using 缓存 " + tempFile);
                    }

                    return tempFile;
                    //包含容易产生异常的代码
                }

                catch
                {
                    Console.WriteLine("发生异常");
                    return null;
                   
                }


              
            }
        }

        public static Stream HttpDownload(string url)
        {
            using (var client = new WebClient())
            {
                string tempFile = Path.GetTempFileName();
                client.DownloadFile(url, tempFile);//下载临时文件
                Console.WriteLine("Using " + tempFile);
                return FileToStream(tempFile, true);
            }
        }
        /// <summary>
        /// 文件转流
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="isDelete">是否删除临时文件</param>
        /// <returns></returns>
        public static Stream FileToStream(string fileName, bool isDelete = false)
        {

            //打开文件

            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);

            // 读取文件的 byte[]

            byte[] bytes = new byte[fileStream.Length];

            fileStream.Read(bytes, 0, bytes.Length);

            fileStream.Close();

            // 把 byte[] 转换成 Stream

            Stream stream = new MemoryStream(bytes);
            if (isDelete)
            {
                File.Delete(fileName);//删除临时文件
            }
            return stream;

        }

            static public string errorWithJsonObject(JObject o)
        {

            string code = String.Empty;
            string code2 = String.Empty;
            string desp = String.Empty;

            if (o["rspCode"] != null)
                code = o["rspCode"].ToString();
            if (o["rspDesc"] != null)
                desp = o["rspDesc"].ToString();
            if (o["code"] != null)
                code2 = o["code"].ToString();

            if (o["Token"] != null)
            {
                string Token = o["Token"].ToString();
                Console.WriteLine(Token);
            }
            
        
            if (code.Equals("0") || code2.Equals("0")) 
                return null;
            if (desp == null)
                desp = "请求失败";
            return desp;
        }

//        -(void) setHttpHeader
//        {
//        
//      
//    if(1)
//    {
//    NSUserDefaults* setting = [NSUserDefaults standardUserDefaults];
//        NSDictionary* requestFields =[setting valueForKey: @"Cookie"];
//        [_sharedClient.requestSerializer setValue:[requestFields objectForKey:@"Cookie"] forHTTPHeaderField:@"Cookie"];
        
        
//        NSString* token = [[TLBConfig shareInstance] getSavedGlobalToken];
//        if(token)
//            [_sharedClient.requestSerializer setValue:token forHTTPHeaderField:@"X-Access-Token"];
//    }

//}

    }



    public static class ComputerInfo
    {
        /// <summary>
        /// 操作系统名称
        /// </summary>
        public static string WinProductName
        {
            get
            {
                if (TryGetRegistryKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", out var productName))
                {
                    return (string)productName;
                }
                return "未知";
            }
        }

        /// <summary>
        /// 操作系统主要版本号
        /// </summary>
        public static uint WinMajorVersion
        {
            get
            {
                if (TryGetRegistryKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentMajorVersionNumber", out var major))
                {
                    return (uint)major;
                }

                if (!TryGetRegistryKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentVersion", out var version))
                    return 0;

                var versionParts = ((string)version).Split('.');
                if (versionParts.Length != 2) return 0;
                return uint.TryParse(versionParts[0], out var majorAsUInt) ? majorAsUInt : 0;
            }
        }

        /// <summary>
        /// 操作系统次要版本号
        /// </summary>
        public static uint WinMinorVersion
        {
            get
            {
                if (TryGetRegistryKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentMinorVersionNumber", out var minor))
                {
                    return (uint)minor;
                }

                if (!TryGetRegistryKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentVersion", out var version))
                    return 0;

                var versionParts = ((string)version).Split('.');
                if (versionParts.Length != 2) return 0;
                return uint.TryParse(versionParts[1], out var minorAsUInt) ? minorAsUInt : 0;
            }
        }

        /// <summary>
        /// 判断是否为Server系统
        /// </summary>
        public static uint IsServer
        {
            get
            {
                if (TryGetRegistryKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "InstallationType",
                        out var installationType))
                {
                    return (uint)(installationType.Equals("Client") ? 0 : 1);
                }

                return 0;
            }
        }

        /// <summary>
        /// 获取注册表值
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <returns>是否成功</returns>
        private static bool TryGetRegistryKey(string path, string key, out dynamic value)
        {
            value = null;
            try
            {
                using (var rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(path))
                {
                    if (rk == null) return false;
                    value = rk.GetValue(key);
                    return value != null;
                }
            }
            catch
            {
                return false;
            }
        }
    }
   
}
